package com.golddaymicromall.activity.salemanager;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.jifenconfirmpay.BonusPointsConfirmPayPwdActivity;
import com.golddaymicromall.activity.panicbuyingconfirmpay.PanicBuyingConfirmPayPwdActivity;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.setting.personal.address.AddressChoiceActivity;
import com.golddaymicromall.adapter.OrderDetailAdapter;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AddressInfo;
import com.golddaymicromall.bean.OrderInfo;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class SaleOrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mOrderDetailBack;

    private OrderDetailAdapter adapter;
    OrderInfo orderInfo = new OrderInfo();
    AddressInfo addressInfo = new AddressInfo();
    List<ProductInfo> listProduct = new ArrayList<ProductInfo>();
    List list = new ArrayList();
    private String orderId;
    private String orderName;
    private String orderType;
    public static final int REQUSET = 1;
    private String addressid;
    float discount;

    private LinearLayout mConfirmPay_ChangeAddress;
    private TextView mUsername;
    private TextView mAddress;
    private TextView mPhone;
    private TextView mCount;
    private TextView mDiscount;
    private TextView mAllPrice;
    private TextView mConfirmPay;
    private TextView mOrderCancel;
    private ListView mOrderDetialLv;
    private TextView mOrderLogstic;
    private LinearLayout mOrderGoPayPwd;
    private ImageView mArrowRight;
    String orderClass;


    //接收返回的值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConfirmPayActivity.REQUSET && resultCode == RESULT_OK) {
            addressid = data.getStringExtra("id");
            String nameAddress = data.getStringExtra("name_address");
            String address = data.getStringExtra("address");
            String phone = data.getStringExtra("phone");
            mUsername.setText("收货人：" + nameAddress);
            mPhone.setText(phone);
            mAddress.setText("地址：" + address);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sale_order_detail);
        initView();
        attemptGetOrderDetail();
    }

    private void initView() {
        orderId = getIntent().getStringExtra("orderId");
        orderName = getIntent().getStringExtra("orderName");
        orderType = getIntent().getStringExtra("orderType");
        orderClass = getIntent().getStringExtra("orderClass");
        mOrderDetailBack = (LinearLayout) findViewById(R.id.sale_orderdetailback);
        mConfirmPay_ChangeAddress = (LinearLayout) findViewById(R.id.orderDetail_changeAddress);
        mUsername = (TextView) findViewById(R.id.orderDetail_username);
        mAddress = (TextView) findViewById(R.id.orderDetail_address);
        mPhone = (TextView) findViewById(R.id.orderDetail_phone);
        mOrderDetialLv = (ListView) findViewById(R.id.orderDetail_listview);
        mAllPrice = (TextView) findViewById(R.id.order_allPrice);
        mCount = (TextView) findViewById(R.id.product_count);
        mDiscount = (TextView) findViewById(R.id.product_discount);
        mConfirmPay = (TextView) findViewById(R.id.orderDetial_confirmpay);
        mOrderCancel = (TextView) findViewById(R.id.orderCancel);
        mOrderLogstic = (TextView) findViewById(R.id.orderDetial_logstic);
        mArrowRight = (ImageView) findViewById(R.id.arrow_right);
        mOrderLogstic.setOnClickListener(this);
        mOrderCancel.setOnClickListener(this);
        mConfirmPay.setOnClickListener(this);
        mOrderDetailBack.setOnClickListener(this);
        mConfirmPay_ChangeAddress.setOnClickListener(this);
        String shopGrade = SPUtils.get(getApplicationContext(), "shop_Grade", "").toString();
        switch (shopGrade) {
            case "1":
                discount = (float) 0.6;
                mDiscount.setText("6折");
                break;
            case "2":
                discount = (float) 0.5;
                mDiscount.setText("5折");
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sale_orderdetailback:
                finish();
                break;
            case R.id.orderDetail_changeAddress:
                Intent intent2choiceaddress = new Intent(this, AddressChoiceActivity.class);
                startActivityForResult(intent2choiceaddress, REQUSET);
                break;
            case R.id.orderDetial_confirmpay:
                if ("3000".equals(orderClass)) {
                    Intent intent4PayPwd = new Intent(SaleOrderDetailActivity.this, BonusPointsConfirmPayPwdActivity.class);
                    intent4PayPwd.putExtra("orderId", orderInfo.getId());
                    startActivity(intent4PayPwd);
                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "积分,订单详情,订单编号：" + orderInfo.getId() + "价格：" + orderInfo.getOrderRealpayment());
                } else if ("5".equals(orderClass)) {
                    Intent intent3PayPwd = new Intent(SaleOrderDetailActivity.this, PanicBuyingConfirmPayPwdActivity.class);
                    intent3PayPwd.putExtra("orderId", orderInfo.getId());
                    startActivity(intent3PayPwd);
                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "抢购,订单详情,订单编号：" + orderInfo.getId() + "价格：" + orderInfo.getOrderRealpayment());
                } else {
                    Intent intent2PayPwd = new Intent(SaleOrderDetailActivity.this, ConfirmPayPwdActivity.class);
                    intent2PayPwd.putExtra("orderId", orderInfo.getId());
                    if ("1".equals(orderType)) {
                        SPUtils.put(getApplicationContext(), "saleflag", "1");
                    } else {
                        SPUtils.put(getApplicationContext(), "saleflag", "0");
                    }
                    startActivity(intent2PayPwd);
                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "二次进货,订单详情,订单编号：" + orderInfo.getId() + "价格：" + orderInfo.getOrderRealpayment());
                }

                break;
            case R.id.orderCancel:
                if ("0".equals(orderInfo.getOrderStatus())) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(SaleOrderDetailActivity.this);
                    builder.setMessage("是否取消订单？\n点击“确定”继续取消，\n点击“取消”返回");
                    builder.setTitle("提示");
                    builder.setPositiveButton("确定", (dialog2, which) -> {
                        dialog2.dismiss();
                        //设置你的操作事项
                        attemptDeleteOrder();
                    });

                    builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
                    builder.create().show();
                } else {
                    finish();
                }
                break;
            case R.id.orderDetial_logstic:
                if ("".equals(orderInfo.getOrderLogisticsid()) || orderInfo.getOrderLogisticsid() == null) {
                    Toast.makeText(SaleOrderDetailActivity.this, "暂无物流信息", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    Intent int2logstic = new Intent(this, LogisticActivity.class);
                    int2logstic.putExtra("orderLogisticsid", orderInfo.getOrderLogisticsid());
                    int2logstic.putExtra("orderId", orderInfo.getOrderName());
                    startActivity(int2logstic);
                }
                break;
            default:
                break;
        }
    }

    //获取订单详情
    public void attemptGetOrderDetail() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.lookorderdetails");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", orderId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(SaleOrderDetailActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(SaleOrderDetailActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list = JSON.parseArray(result);
                            orderInfo = JSON.parseObject(JSON.toJSONString(list.get(0)), OrderInfo.class);
                            addressInfo = JSON.parseObject(JSON.toJSONString(list.get(1)), AddressInfo.class);
                            listProduct = JSON.parseArray(JSON.toJSONString(list.get(2)), ProductInfo.class);
                            addressid = addressInfo.getId();
                            if ("0".equals(orderInfo.getOrderStatus())) {
                                mOrderCancel.setText("取消订单");
                            } else {
                                mOrderCancel.setText("返回列表");
                            }
                            mUsername.setText("收货人：" + addressInfo.getReceivername());
                            mPhone.setText(addressInfo.getPhone());
                            mAddress.setText("地址：" + addressInfo.getCountry() + addressInfo.getProvince() + addressInfo.getCity() + addressInfo.getArea() + addressInfo.getStreet());
                            adapter = new OrderDetailAdapter(listProduct, SaleOrderDetailActivity.this);
                            mOrderDetialLv.setAdapter(adapter);
                            mAllPrice.setText(orderInfo.getOrderRealpayment());
                            mCount.setText("共 " + listProduct.size() + " 种商品");
                            switch (orderInfo.getOrderStatus()) {
                                case "0":
                                    mConfirmPay.setText("确认结算（" + orderInfo.getOrderRealpayment() + ")");
                                    break;
                                case "1":
                                    mConfirmPay.setEnabled(false);
                                    mConfirmPay_ChangeAddress.setEnabled(false);
                                    mArrowRight.setVisibility(View.GONE);
                                    mConfirmPay.setVisibility(View.GONE);
                                    mOrderLogstic.setVisibility(View.VISIBLE);
                                    break;
                                case "3":
                                    mConfirmPay.setEnabled(false);
                                    mConfirmPay_ChangeAddress.setEnabled(false);
                                    mArrowRight.setVisibility(View.GONE);
                                    mConfirmPay.setText("已删除");
                                    break;
                            }
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });


    }

    //取消订单
    public void attemptDeleteOrder() {
        String orderid = orderInfo.getId();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.delete");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", orderid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        switch (result) {
                            case "1":
                                Toast.makeText(SaleOrderDetailActivity.this, "订单已取消,请重新选择产品", Toast.LENGTH_SHORT).show();
                                finish();
                                break;
                            case "0":
                                Toast.makeText(SaleOrderDetailActivity.this, "取消订单失败", Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        attemptGetOrderDetail();
    }
}
